package com.whc.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.whc.api.client.OrdersClient;
import com.whc.api.client.PayClient;
import com.whc.api.dto.PayApplyDTO;
import com.whc.common.context.BaseContext;
import com.whc.common.exception.LoginFailedException;
import com.whc.common.exception.RegisterFailedException;
import com.whc.user.domain.dto.RechargeDto;
import com.whc.user.domain.dto.UserLoginDto;
import com.whc.user.domain.dto.UserRegisterDto;
import com.whc.user.domain.entity.RechargeMessage;
import com.whc.user.domain.entity.User;
import com.whc.api.dto.UserPageVo;
import com.whc.user.domain.vo.UserVo;
import com.whc.user.mapper.RechargeMessageMapper;
import com.whc.user.mapper.UserMapper;
import com.whc.user.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RechargeMessageMapper rechargeMessageMapper;
    @Autowired
    private UserMapper userMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private OrdersClient ordersClient;
    @Autowired
    private PayClient payClient;

    //支付这里包含：减余额，修改支付单和订单状态
    @Override
    public void payMoney(PayApplyDTO payApplyDTO) {
        //见余额
        Long userId= BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if(user.getMoney()<payApplyDTO.getAmount()){
            throw new RuntimeException("账户余额不足");
        }
        user.setMoney(user.getMoney()-payApplyDTO.getAmount());
        userMapper.updateById(user);

        //修改订单状态
        long orderNumber=payApplyDTO.getOrderNumber();
        ordersClient.toPayOrders(orderNumber);
        //修改支付单状态
        long payId = payClient.selectPayByOrderId(orderNumber).getData();
        System.out.println(payId);
        payClient.deletePay(payId);

    }

    public User Login(UserLoginDto dto) {
        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<>();
        lw.eq(User::getUsername,dto.getUsername());

        String password=dto.getPassword();
        User user = userMapper.selectOne(lw);

        //原始密码加密
        password=DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        if(user==null||!password.equals(user.getPassword())){
            throw new LoginFailedException("账号或密码错误");
        }

        return user;
    }

//    public void addUserMoney(long userid,double money){
//        userMapper.addUserMoney(userid,money);
//    }

    @Override
    public UserVo getUserVoById(Long userId) {
        User user = userMapper.selectById(userId);
        UserVo userPageVo = new UserVo();
        BeanUtils.copyProperties(user,userPageVo);
        return userPageVo;
    }

    @Override
    public List<UserPageVo> getUserByIds(List<Long> userIds) {
        List<User> users = userMapper.selectBatchIds(userIds);

        ArrayList<UserPageVo> arr = new ArrayList<>();
        for(User user:users){
            UserPageVo userPageVo = new UserPageVo();
            BeanUtils.copyProperties(user,userPageVo);
            arr.add(userPageVo);
        }
        return arr;
    }

    @Override
    public void recharge(RechargeDto rechargeDto) {
        RechargeMessage rechargeMessage = new RechargeMessage();
        BeanUtils.copyProperties(rechargeDto,rechargeMessage);
        rechargeMessage.setType(1);
        System.out.println(rechargeMessage);
        rechargeMessageMapper.insert(rechargeMessage);
    }

    @Override
    public List<RechargeMessage> selectAllRecharge() {
        List<RechargeMessage> rechargeMessages = rechargeMessageMapper.selectList(null);
        return rechargeMessages;
    }

    @Override
    public void updateRecharge(Long id, Long type) {
        UpdateWrapper<RechargeMessage> updateWrapper = new UpdateWrapper();
        updateWrapper.set("type",type).eq("id",id);
        rechargeMessageMapper.update(null,updateWrapper);
    }

    @Override
    public UserPageVo getUserById(long userId) {
        User user = userMapper.selectById(userId);
        UserPageVo userPageVo = new UserPageVo();
        BeanUtils.copyProperties(user,userPageVo);
        return userPageVo;
    }

    public void Register(UserRegisterDto userRegisterDto){
        String username = userRegisterDto.getUsername();
        LambdaQueryWrapper<User> lw = new LambdaQueryWrapper<User>();
        lw.eq(User::getUsername,username);
        User user1 = userMapper.selectOne(lw);
        if(user1!=null){
            throw new RegisterFailedException("用户已存在");
        }
        String password=userRegisterDto.getPassword();
        User user = new User();
        BeanUtils.copyProperties(userRegisterDto,user);

        //将密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8)));
        user.setCreateTime(LocalDateTime.now());
        user.setMoney(0d);
        user.setType(0);
        userMapper.insert(user);
    }

    @Override
    public User getUserByName(String userName) {
        LambdaQueryWrapper<User> lw=new LambdaQueryWrapper<User>();
        lw.eq(User::getUsername,userName);
        User user = userMapper.selectOne(lw);
        return user;
    }

    @Override
    public List<Integer> getAllUserId() {
        List<Integer> ids = userMapper.getAllUserId();
        return ids;
    }
}
